<template>
  <div class="singer" ref="singer">
    <list-view @select="select" :data="singerlist" class="list-view" ref="list_view"></list-view>
    <router-view/>
  </div>
</template>

<script type="text/ecmascript-6">
import { getSingerList } from '@/api/singer.js'
import { ERR_OK } from '@/api/config'
import pinyin from 'common/js/pinyin'
import Singer from 'common/js/singer'
import ListView from '@/base/listview/listview'
import { mapMutations } from 'vuex'
import { playlistMixin } from 'common/js/mixin'

export default {
  mixins: [playlistMixin],
  components: {
    ListView
  },
  data() {
    return {
      singerlist: []
    }
  },
  methods: {
    handlePlaylist(playlist) {
      if (playlist.length > 0) {
        this.$refs.singer.style.bottom = '60px'
        this.$refs.list_view.refresh()
      } else {
        this.$refs.singer.style.bottom = '0px'
        this.$refs.list_view.refresh()
      }
    },
    select(item) {
      this.setSinger(item)
      this.$router.push({
        path: '/singer/' + item.id,
        params: {},
        query: {}
      })
    },
    _normalizeSingerList(data) {
      const tMap = {}
      const fiSingerList = []
      data.forEach((item) => {
        let tTag = pinyin.getCamelChars(item.singer_name.charAt(0))
        if (!tMap[tTag]) tMap[tTag] = []
        tMap[tTag].push(new Singer(item.country, item.singer_id, item.singer_mid, item.singer_name, item.singer_pic, tTag))
      })
      for (let key in tMap) {
        fiSingerList.push({
          title: key,
          items: tMap[key]
        })
      }
      fiSingerList.sort(function(a, b) {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      this.singerlist = fiSingerList
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    })
  },
  mounted() {
    getSingerList().then((resp) => {
      if (resp.code === ERR_OK) {
        let innerData = resp.singerList.data
        let singerlist = innerData.singerlist
        // let tagIndex = innerData.tags.index
        this._normalizeSingerList(singerlist)
      }
    })
  }
}
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
.singer
  position: fixed
  width: 100%
  top: 88px
  bottom: 0
  overflow: hidden
  .list-view
    height: 100%
</style>
